import React, { useState, useEffect, forwardRef } from 'react';
import { Table, Button, Modal, DatePicker } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import { getGoods, deleteGoods, updateGoods, updateGoodsStatue,searchGoods } from '../../../request/api'
import { useDispatch, useSelector } from 'react-redux';
import './Administration.css'
import { setStoreList, setTableCheck } from '../../../store/module/store';


const App: React.FC = (props, ref) => {
  const dispatch = useDispatch()
  let is_goods = useSelector((state: any) => state.storeList.is_goods)
  let goods_look = useSelector((state: any) => state.storeList.goods_look)

  interface DataType {
    name: String,//商品名称
    description: String,//商品描述
    price: Number,//价格
    discount: Number,//折扣
    //链接type表
    type: String,//商品类型
    img: String,//商品图片
    detailsimg: Array<String>,//商品详情图片
    limited: Number,//限购数量
    sell: Number,//已售数量
    shopid: String,//商品编号
    brand: String,//品牌
    specification: String,//规格
    Production: String,//生产日期
    shelflife: String,//保质期
    storagemode: String,//储存方式
    inventory: Number,//库存
    label: String,//标签
  }


  const columns: TableColumnsType<DataType> = [
    { title: 'ID', dataIndex: 'key', },
    { title: '商品名称', dataIndex: 'name', },
    { title: '原价', dataIndex: 'price', },
    {
      title: '销售价', dataIndex: '',
      render: (text: any) => <span>{(text.price * text.discount).toFixed(2)}</span>//保留两位小数
    },
    { title: '剩余库存', dataIndex: 'inventory', },
    { title: '标签', dataIndex: 'label', },
    { title: '商品分类', dataIndex: 'type', },
    {
      title: '操作', dataIndex: '',
      render: (text: any) =>
        <p>
          <a onClick={() => { updateGoods_statue(text.key) }}>禁用 </a>
          <a onClick={() => { showModal(text) }}>编辑 </a>
          <a onClick={() => { deleteShop(text.key) }}>删除 </a>
        </p>,
    },
  ];


  const [goods_list, setGood_list] = useState([])

  useEffect(() => {
    get_goods()
  }, [is_goods])


  //获取分组列表
  const get_goods = async () => {
    if (goods_look) {
      let res= await searchGoods({goods_look: goods_look})
      setGood_list(res.list)
    }else {
      let res = await getGoods({})
      setGood_list(res.list.filter(item => item.statue === '启用'))
    }
  }

  const dataSource = goods_list.map((item: any) => ({
    key: item._id,
    name: item.name,//商品名称
    description: item.description,//商品描述
    price: item.price,//价格
    discount: item.discount,//折扣
    //链接type表
    type: item.type.type,//商品类型
    img: item.img,//商品图片
    detailsimg: item.detailsimg,//商品详情图片
    limited: item.limited,//限购数量
    sell: item.sell,//已售数量
    shopid: item.shopid,//商品编号
    brand: item.brand,//品牌
    specification: item.specification,//规格
    Production: item.Production,//生产日期
    shelflife: item.shelflife,//保质期
    storagemode: item.storagemode,//储存方式
    inventory: item.inventory,//库存
    label: item.label,//标签
  }))

  //删除商品
  const deleteShop = async (id: String) => {
    const res = await deleteGoods({ id: id })
    if (res.code === 200) {
      alert('删除成功')
      get_goods()
    }
  }

  //修改数据
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [box, setBox] = useState<any>('')
  const [ID, setID] = useState('') //商品id
  const [name, setName] = useState('') //商品名称
  const [specification, setCpecification] = useState('') //规格
  const [price, setPrice] = useState('')  //价格
  const [discount, setDiscount] = useState('')  //折扣
  const [limited, setLimited] = useState('')  //限购数量
  const [label, setLabel] = useState('') //标签
  const [brand, setBrand] = useState('') //品牌


  //展示修改框
  const showModal = (box: any) => {
    setIsModalOpen(true);
    setBox(box) //将当前数据存入box
    setID(box.key) //将当前数据id存入ID
    setName(box.name) //将当前数据名称存入name
    setCpecification(box.specification) //将当前数据规格存入specification
    setPrice(box.price) //将当前数据价格存入price
    setDiscount(box.discount) //将当前数据折扣存入discount
    setLimited(box.limited) //将当前数据限购数量存入limited
    setLabel(box.label)    //将当前数据标签存入label
    setBrand(box.brand) //将当前数据品牌存入brand

  };
  //确定修改
  const handleOk = () => {
    setIsModalOpen(false);
    updateShop()
    setName('')
    setCpecification('')
    setPrice('')
    setDiscount('')
    setLimited('')
    setLabel('')
    setBrand('')

  };

  //修改商品
  const updateShop = async () => {
    const res = await updateGoods({
      _id: ID,
      name: name,
      specification: specification,
      price: price, discount: discount,
      limited: limited,
      label: label,
      brand: brand
    })
    if (res.code === 200) {
      alert('修改成功')
      get_goods()
    }
  }

  //取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
    setName('')
    setCpecification('')
    setPrice('')
    setDiscount('')
    setLimited('')
    setLabel('')
    setBrand('')
  };

  //修改商品状态
  const updateGoods_statue = async (id: string) => {
    const res = await updateGoodsStatue({
      id: id,
      state: '禁用'
    })
    if (res.code === 200) {
      alert('下架成功')
      get_goods()
    }
  }


  return (
    <div>
      <Table<DataType>
        columns={columns}
        dataSource={dataSource}
        pagination={{
          pageSize: 6,
          showQuickJumper: true,
          position: ['bottomLeft']
        }}
      />
      {/* 查看团长信息 */}
      <div>
        <Modal title="查看商品" open={isModalOpen} onOk={handleCancel} onCancel={handleCancel}
          style={{ top: '.5rem' }}
          width={'17.5rem'}
          footer={[
            <Button onClick={handleCancel}>
              取消
            </Button>,
            <Button key="back" type="primary" onClick={handleOk}>
              确定
            </Button>
          ]
          }
        >
          <div className='modal_look'>
            <p style={{ padding: '0.2rem' }}>商品信息</p>
            <div className='modal_look_text'>
              <p>商品ID: {box.key}</p>
              <p>商品名称: <input type="text" placeholder={box.name} value={name} onChange={(e) => setName(e.target.value)} /></p>
              <p>商品规格: <input type="text" placeholder={box.specification} value={specification} onChange={(e) => setStoreList(e.target.value)} /></p>
            </div>
            <p style={{ padding: '0.2rem' }}>商品价格</p>
            <div className='modal_look_text'>
              <p>原价: <input type="text" placeholder={box.price} value={price} onChange={(e) => setPrice(e.target.value)} /></p>
              <p>折扣: <input type="text" placeholder={box.discount} value={discount} onChange={(e) => setDiscount(e.target.value)} /></p>
              <p>限购: <input type="text" placeholder={box.limited} value={limited} onChange={(e) => setLimited(e.target.value)} /></p>
            </div>
            <p style={{ padding: '0.2rem' }}>商品数据</p>
            <div className='modal_look_text'>
              <p>状态: {box.type}</p>
              <p>标签: <input type="text" placeholder={box.label} value={label} onChange={(e) => setLabel(e.target.value)} /></p>
              <p>品牌: <input type="text" placeholder={box.brand} value={brand} onChange={(e) => setBrand(e.target.value)} /></p>
              <div style={{
                padding: '0.3rem',
                width: '96%',
                backgroundColor: 'white',
                marginTop: '0.05rem',
                display: 'flex'
              }}>
                图片:<img src={box.img}
                  style={{ width: '2.7rem', height: '2.7rem', marginLeft: '0.3rem' }} />
              </div>
            </div>
          </div>

        </Modal>
      </div>
    </div >
  );
};

export default App;

